<template>
  <div>
    <!-- 头部登录区域，使用el-row进行布局，两端对齐 -->
    <el-row class="header_login" justify="space-between" align="middle">
        <!-- 左侧返回按钮，点击时触发back方法 -->
        <el-text style="color: white; font-size: 28px; font-weight: bold; cursor: pointer;" @click="back">
            {{ systemName }}
        </el-text>
        <!-- 标题文本，显示"登陆"二字 -->
        <el-text style="color: white;font-size: xx-large; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            padding: 8px 24px; border-radius: 12px; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);">
            登陆
        </el-text>
        <!-- 管理员入口 -->
        <el-button 
            @click="goToAdminLogin" 
            style="background: rgba(255, 255, 255, 0.2); color: white; border: 2px solid white; 
                   border-radius: 8px; font-weight: bold; padding: 10px 20px;">
            <el-icon style="margin-right: 5px;"><User /></el-icon>
            管理员入口
        </el-button>
    </el-row>
    <!-- 登录主体区域 -->
    <el-main class="login_body">
        <!-- 使用el-row进行布局，flex布局，内容居中 -->
        <el-row type="flex" justify="center" style="height: 100%; width: 100%; justify-content: center;" align="center">
            <!-- 左侧装饰区域 -->
            <el-col :span="14" style="height: 100%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; align-items: center; justify-content: center;">
                <el-text style="color: white; font-size: 48px; font-weight: bold; text-align: center;">
                    {{ systemName }}
                </el-text>
            </el-col>
            <!-- 登录内容列，占据10栅格 -->
            <el-col :span="10" style="height: 100%;">
                <!-- 登录内容区域，使用flex布局，内容居中对齐 -->
                <el-row type="flex" justify="center" class="login_content_css" align="middle">
                    <el-col :span="16">
                        <!-- 占位列，确保内容占据整个24栅格宽度 -->
                        <el-col style="width: 100%;" :span="24">
                            <!-- 标题行，显示平台名称 -->
                            <el-row type="flex" justify="center" style="width: 100%;" align="middle">
                                <el-text style="font-size: xx-large; font-weight: bold; text-align: center;">
                                    食速达外卖平台
                                </el-text>
                            </el-row>
                        </el-col>
                        <!-- 登录选项卡，包含短信验证码登陆和密码登陆两种方式 -->
                        <el-tabs type="border-card" style="margin-top: 10%;">
                            <!-- 短信验证码登陆 -->
                            <el-tab-pane label="短信验证码登陆">
                                <!-- 手机号输入框 -->
                                <el-col style="margin-top: 10%;" :span="24">
                                    <el-text style="font-size: large;">
                                        手机号码
                                    </el-text>
                                </el-col>
                                <el-col style="margin-top: 2%;" :span="24">
                                    <el-input v-model="phoneNum" maxlength="11" style="height: 40px;" />
                                </el-col>
                                <el-col style="margin-top: 3%;" :span="24">
                                    <el-text style="font-size: large;">
                                        短信验证码
                                    </el-text>
                                </el-col>
                                <!-- 验证码输入框和发送按钮 -->
                                <el-col style="margin-top: 2%;" :span="24">
                                    <el-row type="flex" justify="space-between" align="middle">
                                        <!-- 验证码输入框 -->
                                        <el-input style="width: 60%; height: 40px;" v-model="verifyCode"
                                            maxlength="6" />
                                        <!-- 发送验证码按钮 -->
                                        <el-button v-model:disabled="isEnable"
                                            style="width: 35%; height: 40px;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                                            border: none; color: white;font-size: large; border-radius: 8px; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);"
                                            @click="getCodeClick">
                                            {{ getVerifyCode }}
                                        </el-button>
                                    </el-row>
                                </el-col>
                                <!-- 注册链接 -->
                                <el-row justify="end" style="margin-top: 5%;">
                                    <el-link :underline="false" @click="register">没有账号？立即注册</el-link>
                                </el-row>
                                <!-- 短信验证码登录按钮 -->
                                <el-col :span="24" style="margin-top: 15%;">
                                    <el-row align="middle" justify="center" type="flex">
                                        <el-button
                                            style="width: 200px;height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                                            border: none; color: white;font-size: large; border-radius: 12px; 
                                            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3); font-weight: 600;"
                                            @click="authByCode">
                                            登入
                                        </el-button>
                                    </el-row>
                                </el-col>
                            </el-tab-pane>
                            
                            <!-- 密码登陆 -->
                            <el-tab-pane label="密码登陆">
                                <!-- 手机号输入框 -->
                                <el-col style="margin-top: 10%;" :span="24">
                                    <el-text style="font-size: large;">
                                        手机号码
                                    </el-text>
                                </el-col>
                                <el-col style="margin-top: 2%;" :span="24">
                                    <el-input v-model="phoneNum" maxlength="11" style="height: 40px;" />
                                </el-col>
                                <!-- 密码输入框 -->
                                <el-col style="margin-top: 3%;" :span="24">
                                    <el-text style="font-size: large;">
                                        密码
                                    </el-text>
                                </el-col>
                                <el-col style="margin-top: 2%;" :span="24">
                                    <el-input v-model="password" maxlength="20" style="height: 40px;" type="password" />
                                </el-col>
                                <!-- 注册链接 -->
                                <el-row justify="end" style="margin-top: 5%;">
                                    <el-link :underline="false" @click="register">没有账号？立即注册</el-link>
                                </el-row>
                                <!-- 密码登录按钮 -->
                                <el-col :span="24" style="margin-top: 15%;">
                                    <el-row align="middle" justify="center" type="flex">
                                        <el-button
                                            style="width: 200px;height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                                            border: none; color: white;font-size: large; border-radius: 12px; 
                                            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3); font-weight: 600;"
                                            @click="authByPwd">
                                            登入
                                        </el-button>
                                    </el-row>
                                </el-col>
                            </el-tab-pane>
                        </el-tabs>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
    </el-main>
    
    <!-- 验证码弹窗组件 -->
    <SmsCodeDialog 
        :visible="smsDialogVisible" 
        @update:visible="(val) => smsDialogVisible = val" 
        :phone="phoneNum"
        @confirm="handleCodeConfirm"
    />
  </div>
</template>


<script lang="ts" setup>
import { ref } from 'vue'// 引入Vue的ref函数，用于创建响应式数据
import { ElMessage, ElNotification } from 'element-plus'// 引入Element Plus UI库的消息和通知组件
import { User } from '@element-plus/icons-vue'// 引入图标
import { systemName } from '../assets/common/Constants.ts';// 引入常量文件
import { useRouter } from 'vue-router';// 引入Vue Router的useRouter函数，用于路由跳转
import { userInfoStore } from '../assets/userStore/userStore.ts';// 引入用户信息状态管理
import { agcApis } from '../assets/apis/AgcApis.ts';// 引入AGC相关API
import { userApis } from '../assets/apis/UserApis.ts';// 引入用户相关API
import { UserModel } from '../assets/models/User.ts';// 引入用户模型
import SmsCodeDialog from '../components/SmsCodeDialog.vue';// 引入短信验证码弹窗组件

// 初始化状态管理实例和路由实例
const userStore = userInfoStore()
const router = useRouter();

// 响应式数据定义
const isEnable = ref<boolean>(false)
const getVerifyCode = ref<string>('获取验证码')
const phoneNum = ref<string>('')
const verifyCode = ref<string>('')
const password = ref<string>('')
const countdownSeconds = ref<number>(60)
let intervalId: any = -1
const smsDialogVisible = ref<boolean>(false)
const currentCode = ref<string>('') // 当前生成的验证码

// 返回主页
const back = () => {
    router.push({ path: '/' })
}

// 跳转到注册页面
const register = () => {
    router.push({ path: '/register' })
}

// 跳转到管理员登录
const goToAdminLogin = () => {
    router.push({ path: '/admin/login' })
}

// 生成6位随机验证码
const generateVerifyCode = () => {
    return Math.floor(100000 + Math.random() * 900000).toString()
}

// 获取验证码
const getCodeClick = () => {
    if (!phoneNum.value) {
        ElMessage.error('请输入手机号码')
        return
    }
    
    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(phoneNum.value)) {
        ElMessage.error('请输入正确的手机号码')
        return
    }
    
    // 先检查手机号是否已注册
    userApis.checkUser(phoneNum.value)
        .then((exists: boolean) => {
            if (!exists) {
                // 手机号未注册
                ElMessage.warning('该手机号尚未注册，请先注册')
                return
            }
            
            // 手机号已注册，发送验证码
            return userApis.sendVerifyCode(phoneNum.value, 'login')
        })
        .then((code) => {
            if (code) {
                // 后端返回的验证码（仅开发环境）
                currentCode.value = code
                console.log('后端返回的验证码：', code)
                
                // 显示验证码弹窗
                smsDialogVisible.value = true
                
                ElMessage.success('验证码已生成')
                
                // 开始倒计时
                isEnable.value = true
                intervalId = setInterval(() => {
                    countdownSeconds.value--
                    getVerifyCode.value = `${countdownSeconds.value}s`
                    if (countdownSeconds.value === 0) {
                        clearInterval(intervalId)
                        isEnable.value = false
                        countdownSeconds.value = 60
                        getVerifyCode.value = '获取验证码'
                    }
                }, 1000)
            }
        })
        .catch((error) => {
            console.error('获取验证码失败：', error)
            ElMessage.error(error.error || '获取验证码失败，请重试')
        })
}

// 处理验证码确认（自动填充）
const handleCodeConfirm = (code: string) => {
    verifyCode.value = code
}

// 通过验证码登录
const authByCode = () => {
    if (!phoneNum.value) {
        ElMessage.warning('手机号码不能为空！')
        return
    }
    
    if (!verifyCode.value) {
        ElMessage.warning('验证码不能为空！')
        return
    }
    
    // 使用后端API进行验证码登录
    userApis.loginByCode(phoneNum.value, verifyCode.value)
        .then((user: UserModel) => {
            // 清除倒计时
            if (intervalId !== -1) {
                clearInterval(intervalId)
                intervalId = -1
            }
            
            // 验证成功，显示通知
            ElNotification({
                title: '登陆成功',
                message: `欢迎回来，${user.username}！`,
                type: 'success',
            })
            
            // 更新用户状态
            userStore.update(user.id, user.username, user.phone, user.head_portrait, user.password)
            
            // 跳转到首页
            router.push({ path: "/" })
        })
        .catch((error) => {
            console.error('登录失败：', error)
            ElMessage.error(error.error || '验证码登录失败，请检查验证码是否正确')
        })
}

// 通过密码登录
const authByPwd = () => {
    if (!phoneNum.value) {
        ElMessage.warning('手机号码不能为空！')
        return
    }
    
    if (!password.value) {
        ElMessage.warning('密码不能为空！')
        return
    }
    
    // 使用后端API进行密码登录
    userApis.loginByPassword(phoneNum.value, password.value)
        .then((user: UserModel) => {
            // 验证成功，显示通知
            ElNotification({
                title: '登陆成功',
                message: `欢迎回来，${user.username}！`,
                type: 'success',
                position: 'bottom-right',
            })
            
            // 更新用户状态
            userStore.update(user.id, user.username, user.phone, user.head_portrait, user.password)
            
            // 跳转到首页
            router.push({ path: "/" })
        })
        .catch((error) => {
            console.error('登录失败：', error)
            ElMessage.error(error.error || '登录失败，请检查手机号和密码是否正确')
        })
}


</script>
<style scoped>
.login_body {
    position: absolute;
    height: 89%;
    width: 100%;
    background: var(--gray-50);
}

.header_login {
    width: 100%;
    height: 90px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.2);
    position: relative;
}

.header_login::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #10B981 0%, #06B6D4 50%, #10B981 100%);
}

/* 登录卡片美化 */
.login_content_css {
    width: 100%;
    height: 100%;
    background: white;
    border-radius: 24px 0 0 24px;
    box-shadow: -8px 0 32px rgba(0, 0, 0, 0.1);
}

/* Tabs 美化 */
:deep(.el-tabs--border-card) {
    border: none !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08) !important;
    border-radius: 16px !important;
}

:deep(.el-tabs__header) {
    background: linear-gradient(135deg, #F0F9FF 0%, #E0E7FF 100%) !important;
    border-radius: 16px 16px 0 0 !important;
    border-bottom: none !important;
}

:deep(.el-tabs__item) {
    color: #4F46E5 !important;
    font-weight: 600 !important;
}

:deep(.el-tabs__item.is-active) {
    background: white !important;
    color: #667eea !important;
}

/* 输入框美化 */
:deep(.el-input__wrapper) {
    border-radius: 8px !important;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
    transition: all 0.3s ease !important;
}

:deep(.el-input__wrapper:focus-within) {
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2) !important;
}

/* 链接美化 */
:deep(.el-link) {
    color: #667eea !important;
    font-weight: 600 !important;
}

:deep(.el-link:hover) {
    color: #764ba2 !important;
}

/* 按钮悬停效果 */
.el-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 16px rgba(102, 126, 234, 0.4) !important;
}
</style>